<?php
require_once $_SESSION["app_root"]."config/app.config.php";
class EntityBLL
{
	function __construct(){
	}
	
	/**
	 * Builds the coresponding EntityInfo DAO for the $ID
	 * @return Returned object is an EntityInfo DAO
	 * @param string $ID is the string representation <b>uuid</b> of the entity
	 * @param object $getFields[optional] if is true it also gets the fields
	 */
	public function GetBaseByID($ID, $getFields = false)
	{
		$entityDao = new EntityDAO();
		return $entity = $entityDao->GetBaseByID($ID, $getFields);
	}
	
	public function GetAll($getFields)
	{
		$entityDao = new EntityDAO();
		return $entity = $entityDao->GetAll();
	}
	
	public function GetAllAsJSON($getFields)
	{
		$nodes = array();
		$entityDao = new EntityDAO();
		$entities = $entityDao->GetAll();
		foreach($entities as $entity){
			$node['text']		= $entity->getPluralLabel();
			$node['id']			= $entity->getID();
			$node['leaf']		= false;
			$node['cls']		= 'file';
			$nodes[] = $node;
		}
		return json_encode($nodes);
	}
	
	public function GetFieldsAsJSON($ID){
		$nodes = array();
		$entityFieldDao = new EntityFieldDAO();
		$entityFields = $entityFieldDao->GetAllByEntityID($ID);
		foreach($entityFields as $field){
			$node['text']		= $field->getName();
			$node['id']			= $field->getID();
			$node['leaf']		= true;
			$node['cls']		= 'file';
			$nodes[] = $node;
		}
		return json_encode($nodes);
	}
	
	public function GetStoreAsJSON($ID){
		$store = "";
		$entityFieldDao = new EntityFieldDAO();
		$entityFields = $entityFieldDao->GetAllByEntityID($ID);
		$store = ", {name: 'ID', type: 'string', mapping: 'ID'}";
		foreach($entityFields as $field){
			$store .= ", {name: '".$field->getDbField()."', type: 'string', mapping: '".$field->getDbField()."'}";
		}
		$store = substr($store, 1);
		$store = "[".$store."]";
		return $store;
	}
	
	public function GetColumnModelAsJSON($ID){
		$store = "";
		$entityFieldDao = new EntityFieldDAO();
		$entityFields = $entityFieldDao->GetAllByEntityID($ID);
		$columnsModel = "{header: '#', readOnly: true, dataIndex: 'ID', width: 50, hidden: false}";
		foreach($entityFields as $field){
			$props = $entityFieldDao->GetFieldGridProperties($field->getID());
			if(sizeof($props)){
				$columnModel = ", dataIndex:'".$field->getDbField()."'";
				foreach($props as $prop){
					$columnModel .= ", ".$prop['Name'].":'".$prop["Value"]."'";
				}
				$columnModel = substr($columnModel, 1);
				$columnModel =", {".$columnModel."}";
				$columnsModel .= "".$columnModel;
			}
		}
		$columnsModel = "[".$columnsModel."]";
		return $columnsModel;
	}
	public function GetFormFieldsAsJSON($ID){
		$entityFieldDao = new EntityFieldDAO();
		$entityFields = $entityFieldDao->GetAllByEntityID($ID);
		return $entityFields;
	}
	public function GetRecordsAsJSON($entityID, $start, $limit, $queryString=null){
		$entityDao = new EntityDAO();
		$entityRecords = $entityDao->GetRecords($entityID, $start, $limit, $queryString);
		return $entityRecords;
		/*
		$count = "SELECT COUNT(ID) FROM tblspecificatii";
		$query = "
				SELECT ID, SpecName FROM tblspecificatii LIMIT $start, $limit
				";
		$db = GetDatabase();
		$counter = $db->Execute($count);
		$rs = $db->Execute($query);
		$result = array();
		$counterArr = $conter->GetArray();
		$result["TotalRecords"] = $counterArr[0]["COUNT(ID)"];
		$result["Records"] = $rs->GetArray();
		return $result;
		*/
		//vp($arr);
	}
	
	
	/*
	public function GetBaseByID($ID, $getFields = false)
    {
    	$entity = null;
    	$db = GetDatabase();
		$query = "SELECT * FROM cms_entities WHERE id = '".$ID."'";
		$rs = $db->SelectLimit($query, 1, 0);
		$result = $rs->FetchRow();
		if($result){
			$entity = $this->EntityDataReader($result);
		}
		if($getFields && $entity != null)
		{
			$entityFields = new EntityFieldBLL();
			$entity->setFields($entityFields->GetAllByEntityID($ID, "grid_location"));
		}
		$db->close();
		return $entity;
    }
	*/
	public function EntityDataReader($result){
		$entity = new EntityDVO(	$result['ID'], 
									$result['Name'],
									$result['Label'],
									$result['PluralLabel']);
		return $entity;
	}
	
	
	public function Create($Name, $Label, $PluralLabel, $TableName){
		global $EntityStatusEnum;
		$userID = $_SESSION["SessionUser"]->getID();
		$userGroupID = $_SESSION["SessionUser"]->getGroupID();
		$now = time();
		$_tableName = $TableName;
		$_tableName = stripslashes ($_tableName);
		$_tableName = preg_replace('~^(\s*)(.*?)(\s*)$~m', "\\2", $_tableName);
		$_tableName = ereg_replace("[^[:alnum:] ]","",$_tableName);
		$_tableName = preg_replace("/\s\s+/", " ", $_tableName);
		$_tableName = str_replace(" ", "_", $_tableName);
		$_tableName = strtolower($_tableName);
		
		$entityData = new EntityDVO();
		$entityData->setID(uuid());
		$entityData->setName($Name);
		$entityData->setLabel($Label);
		$entityData->setPluralLabel($PluralLabel);
		$entityData->setTableName($_tableName);
		$entityData->setCreatedBy($userID);
		$entityData->setCreatedDate($now);
		$entityData->setModifiedBy($userID);
		$entityData->setModifiedDate($now);
		$entityData->setOwnerID($userID);
		$entityData->setGroupID($userGroupID);
		$entityData->setStatus($EntityStatusEnum["Normal"]);
		$entityData->setU(7);
		$entityData->setG(7);
		$entityData->setW(1);
		$entity = new EntityDAO();
		return $entity->Create($entityData);
	}
	
	public function AddField($EntityID, $FieldType, $Name, $DbField=null, $GridLocation=null, $FormLocation=null){
		global $EntityStatusEnum;
		if($DbField == null){
			$DbField = $Name;
		}
		$DbField = stripslashes ($DbField);
		$DbField = preg_replace('~^(\s*)(.*?)(\s*)$~m', "\\2", $DbField);
		$DbField = ereg_replace("[^[:alnum:] ]","",$DbField);
		$DbField = preg_replace('/\s\s+/', ' ', $DbField);
		$userID = $_SESSION["SessionUser"]->getID();
		$now = time();
		
		$entityFieldDVO = new EntityFieldDVO();
		$entityFieldDVO->setID(uuid());
		$entityFieldDVO->setEntityID($EntityID);
		$entityFieldDVO->setFieldType($FieldType);
		$entityFieldDVO->setName($Name);
		$entityFieldDVO->setDbField($DbField);
		$entityFieldDVO->setGridLocation($GridLocation);
		$entityFieldDVO->setFormLocation($FormLocation);
		$entityFieldDVO->setCreatedBy($userID);
		$entityFieldDVO->setCreatedDate($now);
		$entityFieldDVO->setModifiedBy($userID);
		$entityFieldDVO->setModifiedDate($now);
		$entityFieldDVO->setOwnerID($userID);
		$entityFieldDVO->setStatus($EntityStatusEnum["Normal"]);
		$entityFieldDVO->setU(7);
		$entityFieldDVO->setG(7);
		$entityFieldDVO->setW(1);
		//vp($entityFieldDVO);
		$entityField = new EntityFieldDAO();
		$entityField->Create($entityFieldDVO);
	}
	
	public static function AddRecord($recordData = null, $files = null){
		$result["success"] = false;
		$result["message"] = "Failed saving the record";
		$fieldsArr = array();
		if($recordData == null){
			$result["message"] .= "<br> * The data did not reach the server.";
			return $result;
		}
		$field = new EntityFieldDAO();
		foreach($recordData as $fieldID => $value){
			$field = EntityFieldBLL::GetByID($fieldID, false, true);
			$field->setValue($recordData[$fieldID]);
			array_push($fieldsArr, EntityFieldBLL::PharseForStorage($field));
		}
		//$tst = array();
		$fileFieldID = "";
		if(sizeof($files) > 0){
			foreach($files as $fileFieldID => $fileData){
				$fileField = EntityFieldBLL::GetByID($fileFieldID, false, true, true);
				$fileField->setValue($fileData["name"]);
				array_push($fieldsArr, $fileField);
			}
		}
		/*
		 * @todo _Apply security
		 */
		$entityRecordDAO = new EntityRecordDAO();
		foreach($fieldsArr as $field){
			$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, $field->getDbField(), $field->getValue());
		}
		$entityDao = new EntityDAO();
		//$entityRecordDVO = new EntityRecordDVO();
		
		$userGroupID = $_SESSION["SessionUser"]->getGroupID();
		$userID = $_SESSION["SessionUser"]->getID();
		$now = time();
		
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "ID", uuid());
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "CreatedBy", $userID);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "CreatedDate", $now);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "ModifiedBy", $userID);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "ModifiedDate", $now);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "OwnerID", $userID);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "GroupID", $userGroupID);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "Status", 1);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "u", 7);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "g", 7);
		$entityRecordDVO = EntityRecordDAO::PushValue($entityRecordDVO, "w", 7);
		
		$entity = $entityDao->GetBaseByID($fieldsArr[0]->getEntityID());
		$tableName = $entity->getTableName();
		$insertResult = EntityRecordDAO::InsertRecord($entityRecordDVO, $tableName);
		$result = $insertResult;
		return $result;
	}
}
?>
